package com.xzbd.gef.model.connection;

import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.xzbd.core.gef.Node;

public class ConnectionPort extends Node {

	private static final long serialVersionUID = 1L;

	public static final String PDP_SOURCE = "pdp_source";
	public static final String PDP_TARGET = "pdp_target";
	public static final String P_CONSTRAINT = "_constraint";

	private Rectangle constraint;
	private List<AbstractConnectionModel> inputs = new ArrayList<AbstractConnectionModel>();
	private List<AbstractConnectionModel> outputs = new ArrayList<AbstractConnectionModel>();

	public Rectangle getConstraint() {
		return constraint;
	}

	public void setConstraint(Rectangle constraint) {
		if (constraint.x < 0) {
			constraint.x = 0;
		}
		if (constraint.y < 0) {
			constraint.y = 0;
		}
		this.constraint = constraint;
		firePropertyChange(P_CONSTRAINT, null, constraint);
	}

	public static String getpConstraint() {
		return P_CONSTRAINT;
	}

	public void setInputs(List<AbstractConnectionModel> inputs) {
		this.inputs = inputs;
	}

	public void setOutputs(List<AbstractConnectionModel> outputs) {
		this.outputs = outputs;
	}

	public List<AbstractConnectionModel> getInputs() {
		return inputs;
	}

	public List<AbstractConnectionModel> getOutputs() {
		return outputs;
	}

	public void addIn(AbstractConnectionModel model) {
		if (!inputs.contains(model)) {
			inputs.add(model);
			firePropertyChange(PDP_TARGET, null, model);
		}
	}

	public void addOut(AbstractConnectionModel model) {
		if (!outputs.contains(model)) {
			outputs.add(model);
			firePropertyChange(PDP_SOURCE, null, model);
		}
	}

	public void removeInput(AbstractConnectionModel model) {
		if (inputs.contains(model)) {
			inputs.remove(model);
			firePropertyChange(PDP_TARGET, model, null);
		}
	}

	public void removeOut(AbstractConnectionModel model) {
		if (outputs.contains(model)) {
			outputs.remove(model);
			firePropertyChange(PDP_SOURCE, model, null);
		}
	}

	public List<Node> getSourceNodes() {
		List<Node> nodes = new ArrayList<Node>();
		if (Objects.isNull(inputs)) {
			return nodes;
		}
		inputs.forEach(out -> {
			nodes.add(out.getSrc());
		});
		return nodes;
	}

	public List<Node> getTargetNodes() {
		List<Node> nodes = new ArrayList<Node>();
		if (Objects.isNull(outputs)) {
			return nodes;
		}
		outputs.forEach(out -> {
			nodes.add(out.getTarget());
		});
		return nodes;
	}

}
